package com.hh.TreeQuestions;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author hanghao
 * @Date 2023/7/6 15:50
 * @Version 1.0
 * 从中序与后序遍历序列构造二叉树
 * middle
 */

public class No106 {
    Map<Integer,Integer> map = new HashMap<>();
    public TreeNode buildTree(int[] inorder, int[] postorder) {
        for (int i = 0; i < inorder.length; i++) {
            map.put(inorder[i], i);
        }
        return findNode(inorder,0, inorder.length, postorder,0, postorder.length);
    }

    public TreeNode findNode(int[] inorder, int inBegin, int inEnd, int[] postorder, int postBegin, int postEnd) {
        if (inBegin >= inEnd || postBegin >= postEnd) return null;
        Integer rootIndex = map.get(postorder[postEnd - 1]); //因为是前闭后开，所以这里要取到最后一个数要减一
        TreeNode root = new TreeNode(inorder[rootIndex]);
        int leftLen = rootIndex - inBegin;
        root.left = findNode(inorder,inBegin,rootIndex,postorder,postBegin,postBegin + leftLen);
        root.right = findNode(inorder,rootIndex + 1, inEnd,postorder,postBegin + leftLen, postEnd - 1);
        return root;
    }
}
